
const { doSearchSysPlugin } = require('./doSearchSysPlugin');
const { doOrderPlugin } = require('./doOrderPlugin');
const { filterByKeyword } = require('../../../common/utils/searchUtil');
const { getLocalPluginByKeywordInitials } = require('../../../core/pluginSearchService/getLocalPluginByKeyword');
const { onEmit } = require('../../baseService/broadService/processor/broadcastProcessor');
const { asyncTopicConstants } = require('../../../common/constans/asyncTopicContans');
const EnvContext = require('../../../common/context/EnvContext');
const { setHeighByRow } = require('../../../common/utils/mainWinUtil');
const { getMainPreloadJsPath } = require('../../../common/utils/fileUtil')


exports.doSearchByKeyword = async function (request) {
    // decisionMethod: "string",     // 决策方法：根据正则，首写字母，文件类型等方法，对输入数据进行决策是否需要执行该命令
    // decisionDataType: "string",   // 决策数据类型：keyword，file，folder
    // decisionDataSource: "string", // 决策数据源：search(主窗口关键字搜索)，hover（鼠标选中），clipboard（粘贴板内存）
    // decisionData: "string",       // 决策数据：如果是关键字直接填字符串，如果是正则直接填正则表达式，如果是

    const source = request.source

    if (request.input == "") {
        onEmit(asyncTopicConstants.onSearchPlugin, [])
        return
    }

    if (source == "search") {
        preprocessForPanel(request)
        preprocessForSearch(request)
        // searchSysPlugin(request)
        searchLocalPlugin(request)
        searchLocalPluginForPanel(request)
        return
    }


    if (source == "hover") {
        preprocessForPanel(request)
        // searchSysPlugin(request)
        searchLocalPluginForPanel(request)
        return
    }
}






function searchSysPlugin(request) {
    const appPlugin = doSearchSysPlugin()
    const resultData = doOrderAndFilterPLugin(appPlugin, request)
    const preloadPath = getMainPreloadJsPath()
    onEmit(asyncTopicConstants.onSearchPlugin, { cmdInfos: resultData, preloadPath: preloadPath })
}


async function searchLocalPlugin(request) {

    const appPlugin = await getLocalPluginByKeywordInitials(request.input)
    const resultData = doOrderAndFilterPLugin(appPlugin, request)
    const preloadPath = getMainPreloadJsPath()
    onEmit(asyncTopicConstants.onSearchPlugin, { cmdInfos: resultData, preloadPath: preloadPath })
}


async function searchLocalPluginForPanel(request) {

    const appPlugin = await getLocalPluginByKeywordInitials(request.input)
    const resultData = doOrderAndFilterPLugin(appPlugin, request)
    const preloadPath = getMainPreloadJsPath()
    onEmit(asyncTopicConstants.onSearchPluginForPanel, { cmdInfos: resultData, preloadPath: preloadPath })
}





function preprocessForPanel(request) {
    const keyword = request.input
    let translateData = doPreprocessForTranslate(require)
    const retData = getFirstNotNull(translateData)

    if (retData) {
        onEmit(asyncTopicConstants.onPreProcessForPanel, retData)
    }
}



function doPreprocessForTranslate(request) {
    try {
        const keyword = request.input
        const to = "翻译; 译; 被翻译; 被译成; (使)转变，变为; （以某种方式）理解;"
        const data = { type: "translate", data: { from: keyword, to: to } }
        return data
    } catch (e) {
        return null
    }

}


function preprocessForSearch(request) {
    let calcData = doPreSearchForCalc(request)
    let jsonData = doPreSearchForJson(request)

    const retData = getFirstNotNull(calcData, jsonData)


    if (retData) {
        onEmit(asyncTopicConstants.onPreSearch, retData)
    } else {
        onEmit(asyncTopicConstants.onPreSearch, "")
    }
}


function checkNum(c) {
    var r = /^[1-9]?[0-9]*\.[0-9]*$/;
    return r.test(c);
}


function doPreSearchForCalc(request) {
    const keyword = request.input
    let retData = null
    // 如果只是输入数字不计算
    if (checkNum(keyword)) {
        return null
    }

    try {
        result = eval(keyword)
        if (typeof result === 'number' && !isNaN(result)) {
            retData = result
            return { data: retData, type: "number" }
        }
    } catch (e) { }
    return null
}


function doPreSearchForJson(request) {
    const keyword = request.input
    if (typeof keyword == 'string') {
        try {
            JSON.parse(keyword);
            return { data: JSON.stringify(JSON.parse(keyword), null, 4), type: "json" }
        } catch (e) {
            return null;
        }
    }
    return null
}



function doOrderAndFilterPLugin(plugins, request) {
    plugins = filterByKeyword(plugins, null)
    plugins = doOrderPlugin(plugins)
    return plugins
}



function getFirstNotNull() {
    var length = arguments.length;
    for (var i = 0; i < length; i++) {
        if (arguments[i] != null) {
            return arguments[i]
        }
    }
    return null
}

